package top.codetheory.thread._007_单例;

import lombok.extern.slf4j.Slf4j;

/**
 * @author:
 * @since: 2024/5/24 下午2:55
 **/
@Slf4j
public class _002_可见性 {
    static int x;


    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            test();
            x = 0;
        }
    }

    public static void test() {
        Thread t2 = new Thread(()->{
            while(true) {
                if(Thread.currentThread().isInterrupted()) {  // JVM会确保所有在interrupt方法调用前的操作（包括对共享变量的修改）对被interrupt的线程可见。
                    log.info(String.valueOf(x));
                    break;
                }
            }
        },"t2");
        t2.start();

        new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            x = 10;
            t2.interrupt();  // 1s 后打断t2线程
        },"t1").start();

        while(!t2.isInterrupted()) {  // 等待t2线程打断
            Thread.yield();
        }
        log.info(String.valueOf(x));
    }
}